import React, { useState, useEffect } from "react";
import { Calendar, Flex, Space } from "antd";
import dayjs, { Dayjs } from "dayjs";
import dateDisabled from "@/assets/image/icons/date-disabled.svg";
interface DualCalendarProps {
  onDateSelect: (date: Dayjs | null) => void; // 选中的日期回调，允许传递 null
}

import styled from "styled-components";
import { getQuota } from "@/services/carPark";
import useParkStore from "@/store/parkStore";
import { QuotaParams } from "../type";

const CustomCalendar = styled(Calendar)`
  .ant-picker-panel {
    border-top: none !important; /* 使用 !important 强制覆盖 */
  }
`;

const StyledHeaderTitle = styled("div")`
  font-family: Montserrat;
  font-size: 18px;
  font-weight: 400;
  line-height: 24px;
  color: #7a6145;
`;

const DualCalendar: React.FC<DualCalendarProps> = ({ onDateSelect }) => {
  const { vehType, parkId } = useParkStore();
  const today = dayjs(); // 当前日期
  const [isFirstLoad, setIsFirstLoad] = useState(true);
  const [effectiveDateData, setEffectiveDateData] = useState<QuotaParams[]>([]);
  // 格式化当前日期
  const startDate = today.format("YYYY-MM-DD"); // 当前月，例如 2024-10-23
  const endDate = today.add(13, "day").format("YYYY-MM-DD"); // 14 天后的日期，例如 2024-11-06
  const startOfCurrentMonth = today.startOf("month"); // 当前月的开始
  const startOfNextMonth = today.add(1, "month").startOf("month"); // 下个月的开始
  const currentMonth = today.startOf("month"); // 当前月的开始
  const nextMonth = today.add(1, "month").startOf("month"); // 下个月的开始
  // 将 effectiveDateData 转换为一个对象以便查找
  const effectiveDateMap = effectiveDateData.reduce(
    (acc: any, { effectiveDate, full }) => {
      acc[effectiveDate] = full;
      return acc;
    },
    {}
  );
  const disabledDate = (date: Dayjs) => {
    const dateString = date.format("YYYY-MM-DD"); // 获取当前日期的字符串格式
    const isFullDate = effectiveDateMap[dateString]; // 检查该日期是否为 full
    // 返回 true 表示该日期被禁用
    return (
      date.isBefore(startDate, "day") ||
      date.isAfter(endDate, "day") ||
      isFullDate // 如果是 full 日期也禁用
    );
  };
  // 独立状态管理两个日历的选中日期
  const [leftSelectedDate, setLeftSelectedDate] = useState<Dayjs | null>(
    // today.add(1, "day")
    today
  ); // 初始化左侧日历为当前日的下一天
  const [rightSelectedDate, setRightSelectedDate] = useState<Dayjs | null>(
    null
  ); // 初始化右侧日历为空

  useEffect(() => {
    // 选中日期变更时更新父组件
    onDateSelect(leftSelectedDate || rightSelectedDate);
  }, [leftSelectedDate, rightSelectedDate, onDateSelect]);
  useEffect(() => {
    if (!isFirstLoad) {
      getQuota({
        startDate: startDate,
        endDate: endDate,
        parkId,
        vehType,
      })
        .then((data) => {
          console.log(data, "data1111111");
          setEffectiveDateData(data.data);
        })
        .catch((error) => {
          console.error("Error fetching code and picture:", error);
        });
    } else {
      // 首次加载完成后设置 isFirstLoad 为 false
      setIsFirstLoad(false);
    }
  }, [parkId, vehType]);

  const handleLeftDateSelect = (date: Dayjs) => {
    setLeftSelectedDate(date); // 设置左侧日历的选中日期
    setRightSelectedDate(null); // 清空右侧日历的选中日期
  };

  const handleRightDateSelect = (date: Dayjs) => {
    setRightSelectedDate(date); // 设置右侧日历的选中日期
    setLeftSelectedDate(null); // 清空左侧日历的选中日期
  };

  const renderCalendar = (calendarId: "left" | "right", month: Dayjs) => {
    // 获取相应月份的显示名称
    const monthToDisplay = calendarId === "left" ? currentMonth : nextMonth;
    const headerTitle = monthToDisplay.format("MMMM YYYY"); // 格式化为 "October 2024" 或 "November 2024"

    return (
      <CustomCalendar
        onSelect={
          calendarId === "left" ? handleLeftDateSelect : handleRightDateSelect
        } // 选择日期时更新对应日历的选中状态
        fullscreen={false}
        style={{
          border: "1px solid #fff", // 统一边框
          margin: "10px",
          cursor: "pointer",
        }}
        disabledDate={disabledDate}
        headerRender={() => (
          <div style={{ textAlign: "center", fontWeight: "bold" }}>
            <StyledHeaderTitle>{headerTitle}</StyledHeaderTitle>
          </div>
        )}
        fullCellRender={(date) => {
          const dateString = date.format("YYYY-MM-DD"); // 获取当前日期的字符串格式
          const isFullDate = effectiveDateMap[dateString]; // 检查该日期是否为 full

          return (
            <div
              style={{
                width: "100%",
                height: "32px",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                position: "relative", // 用于绝对定位斜线
              }}
            >
              {isFullDate && (
                <div
                  style={{
                    position: "absolute",
                    top: "50%",
                    left: "50%",
                    width: "24px", // 圆圈的直径
                    height: "24px",
                    background: `url(${dateDisabled}) no-repeat center center`, // 使用您的图片路径
                    backgroundSize: "cover", // 确保图片覆盖整个圆圈
                    // borderRadius: "50%", // 圆形
                    transform: "translate(-50%, -50%)", // 使圆心居中
                    opacity: 0.5, // 设置透明度
                  }}
                ></div>
              )}
              <div
                style={{
                  position: "relative",
                  zIndex: 2,
                  background:
                    (calendarId === "left" &&
                      leftSelectedDate &&
                      leftSelectedDate.isSame(date, "day")) ||
                    (calendarId === "right" &&
                      rightSelectedDate &&
                      rightSelectedDate.isSame(date, "day"))
                      ? "#7A6145"
                      : undefined,
                  width: "24px",
                  height: "24px",
                  borderRadius: "50%",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                {date.date()}
              </div>
            </div>
          );
        }}
        // 设置日历显示的当前月份
        //@ts-ignore
        value={
          calendarId === "left" ? leftSelectedDate : rightSelectedDate || month
        }
      />
    );
  };

  return (
    <Flex align="center" justify="center">
      <Space size={"large"}>
        {renderCalendar("left", startOfCurrentMonth)}
        {renderCalendar("right", startOfNextMonth)}
      </Space>
    </Flex>
  );
};

export default DualCalendar;
